<script setup>
import { ref, onMounted } from "vue";

import * as tools from "@/test/AI/tools";
import ToolsConfig from "@/test/AI/Tools.json";
import { ElMessage as Message } from "element-plus";
const isLoading = ref(false);

// 语音识别相关状态
const isListening = ref(false);
const transcript = ref("");
const userInput = ref("");
const aiResponse = ref("");

// 语音识别实例
let recognition = null;

// 初始化语音识别
const initSpeechRecognition = () => {
  if ("webkitSpeechRecognition" in window) {
    // chrome中无效
    recognition = new webkitSpeechRecognition();
    recognition.continuous = false;
    recognition.interimResults = true;
    recognition.lang = "zh-CN";

    recognition.onresult = event => {
      const result = event.results[0][0].transcript;
      transcript.value = result;
      userInput.value = result;
      console.log(result);
    };

    recognition.onend = () => {
      isListening.value = false;
    };
  } else {
    console.error("浏览器不支持语音识别");
  }
};

// 开始语音识别
const startListening = () => {
  if (recognition) {
    isListening.value = true;
    transcript.value = "";
    recognition.start();
  }
};

// 停止语音识别
const stopListening = () => {
  if (recognition) {
    recognition.stop();
    isListening.value = false;
  }
};

// 调用AI模型API
const callAIModel = async () => {
  isLoading.value = true;

  const queryData = {
    model: "deepseek-chat",
    messages: [{ role: "user", content: userInput.value }],
    tools: ToolsConfig,
    tool_choice: "auto",
  };

  try {
    // 这里需要替换为实际的deepseek API调用
    const response = await fetch("https://api.deepseek.com/chat/completions", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: "Bearer sk-dfc55786f1ca450b8903a0f7f138dff2",
      },
      body: JSON.stringify(queryData),
    });
    const data = await response.json();
    handleAIResponse(data);
    // aiResponse.value = data?.choices?.[0]?.message?.content;
  } catch (error) {
    console.error("AI调用出错:", error);
    aiResponse.value = "抱歉,处理您的请求时出现错误";
  } finally {
    isLoading.value = false;
  }
};

// 处理AI的返回值
const handleAIResponse = response => {
  const finish_reason = response?.choices?.[0].finish_reason;

  if (finish_reason === "tool_calls") {
    const tool_call = response?.choices?.[0].message.tool_calls[0];
    const tool_name = tool_call.function.name;
    const tool_args = JSON.parse(tool_call.function.arguments);

    console.log(tool_name, tool_args);

    if (tool_name === "flyTo") {
      tools.flyTo(window.map, tool_args.location);

      Message.success("已飞到" + tool_args.location);
    }
  } else if (finish_reason === "stop") {
    aiResponse.value = response?.choices?.[0]?.message?.content;
  }
};

// 提交用户输入
const handleSubmit = async () => {
  if (userInput.value.trim()) {
    await callAIModel();
  }
};

// 组件挂载时初始化语音识别
onMounted(() => {
  initSpeechRecognition();
});
</script>

<template>
  <div class="ai-control-panel" v-loading="isLoading">
    <div class="input-section">
      <el-input
        v-model="userInput"
        type="textarea"
        :rows="3"
        placeholder="请输入您的指令..." />
      <div class="button-group">
        <el-button
          :type="isListening ? 'danger' : 'primary'"
          @click="isListening ? stopListening() : startListening()">
          {{ isListening ? "停止语音输入" : "开始语音输入" }}
        </el-button>
        <el-button type="primary" @click="handleSubmit">发送</el-button>
      </div>
    </div>

    <div class="output-section">
      <h3>AI助手回应：</h3>
      <div class="response-area">
        {{ aiResponse }}
      </div>
    </div>
  </div>
</template>

<style scoped>
.ai-control-panel {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.input-section {
  margin-bottom: 20px;
}

.button-group {
  margin-top: 10px;
  display: flex;
  gap: 10px;
}

.output-section {
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
}

.response-area {
  min-height: 100px;
  padding: 10px;
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}
</style>
